<template>
	<view class="container">
		<view class="header">
			<text class="title">我的虚拟号码</text>
		</view>
		
		<view class="number-list">
			<view class="number-item" v-for="(item, index) in virtualNumbers" :key="index">
				<view class="number-info">
					<text class="number">{{ item.number }}</text>
					<text class="status" :class="{ 'active': item.status === '启用', 'inactive': item.status === '停用' }">
						{{ item.status }}
					</text>
				</view>
				<view class="number-actions">
					<button 
						class="action-btn" 
						:class="{ 'danger': item.status === '启用' }"
						@click="toggleStatus(index)"
					>
						{{ item.status === '启用' ? '停用' : '启用' }}
					</button>
					<button class="action-btn delete" @click="deleteNumber(index)">删除</button>
				</view>
			</view>
		</view>
		
		<view class="form-container">
			<view class="form-item">
				<text class="label">等级</text>
				<picker class="picker" @change="onLevelChange" :value="levelIndex" :range="levelOptions">
					<view class="picker-view">{{ levelOptions[levelIndex] }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="label">虚拟号码</text>
				<view class="number-input-container">
					<input class="input" type="text" v-model="generatedNumber" placeholder="点击生成按钮生成虚拟号码" disabled />
					<button class="refresh-btn" @click="refreshNumber">刷新</button>
				</view>
			</view>
			<view class="form-item">
				<text class="label">费率</text>
				<input class="input" type="digit" v-model="newRate" placeholder="费率" disabled />
			</view>
			<view class="form-item">
				<text class="label">状态</text>
				<picker class="picker" @change="onStatusChange" :value="statusIndex" :range="statusOptions">
					<view class="picker-view">{{ statusOptions[statusIndex] }}</view>
				</picker>
			</view>
			<button class="add-btn" @click="addNumber">添加</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				virtualNumbers: [],
				levelOptions: ['普通', '高级'],
				levelIndex: 0,
				generatedNumber: '', // 生成的虚拟号码
				newRate: 10,
				statusOptions: ['启用', '停用'],
				statusIndex: 0
			}
		},
		onLoad() {
			// 页面加载时获取虚拟号码列表
			this.fetchVirtualNumbers();
		},
		methods: {
			// 获取虚拟号码列表
			async fetchVirtualNumbers() {
				try {
					// 从本地存储获取用户手机号
					const localUserInfo = uni.getStorageSync('userInfo');
					if (!localUserInfo || !localUserInfo.phone) {
						uni.showToast({
							title: '未找到用户手机号',
							icon: 'none'
						});
						return;
					}
					
					// 调用API获取虚拟号码列表
					const response = await this.getVirtualNumbersByPhone(localUserInfo.phone);
					
					if (response.code === 0) {
						// 转换数据格式以适配现有UI
						this.virtualNumbers = response.data.map(item => ({
							number: item.virtualNumber,
							status: item.status === 1 ? '启用' : '停用',
							level: item.level,
							rate: item.rate,
							createTime: item.createTime,
							updateTime: item.updateTime
						}));
					} else {
						uni.showToast({
							title: response.msg || '获取虚拟号码列表失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取虚拟号码列表异常:', error);
					uni.showToast({
						title: '网络请求异常',
						icon: 'none'
					});
				}
			},
			
			// 调用获取虚拟号码接口
			getVirtualNumbersByPhone(phoneNumber) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:6002/user-client/api/virtualNumber/getByPhoneNumber?phoneNumber=' + phoneNumber,
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						success: (res) => {
							resolve(res.data);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			
			// 调用创建虚拟号码接口
			addVirtualNumber(data) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:6002/user-client/api/virtualNumber/add',
						method: 'POST',
						data: data,
						header: {
							'Content-Type': 'application/json'
						},
						success: (res) => {
							resolve(res.data);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			
			// 调用更新虚拟号码状态接口
			updateVirtualNumberStatus(virtualNumber, status) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:6002/user-client/api/virtualNumber/updateStatus?virtualNumber=' + encodeURIComponent(virtualNumber) + '&status=' + status,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							resolve(res.data);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			
			// 调用删除虚拟号码接口
			deleteVirtualNumber(virtualNumber) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:6002/user-client/api/virtualNumber/delete?virtualNumber=' + encodeURIComponent(virtualNumber),
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							resolve(res.data);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			
			// 等级选择变更处理
			onLevelChange(e) {
				this.levelIndex = e.detail.value;
				// 根据选择的等级自动设置费率
				this.newRate = this.levelIndex === 0 ? 10 : 20;
				// 重新生成号码
				this.refreshNumber();
			},
			
			// 状态选择变更处理
			onStatusChange(e) {
				this.statusIndex = e.detail.value;
			},
			
			// 生成随机虚拟号码
			generateVirtualNumber() {
				if (this.levelIndex === 0) {
					// 普通等级：8-11位随机数字
					const length = Math.floor(Math.random() * 4) + 8; // 8到11之间的随机数
					let number = '';
					for (let i = 0; i < length; i++) {
						number += Math.floor(Math.random() * 10);
					}
					return number;
				} else {
					// 高级等级：类似真实号码的格式（以1开头的11位手机号）
					const prefixes = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', 
									'150', '151', '152', '153', '155', '156', '157', '158', '159',
									'170', '171', '173', '175', '176', '177', '178',
									'180', '181', '182', '183', '184', '185', '186', '187', '188', '189',
									'191', '193', '195', '196', '197', '198', '199'];
					const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
					let suffix = '';
					for (let i = 0; i < 8; i++) {
						suffix += Math.floor(Math.random() * 10);
					}
					return prefix + suffix;
				}
			},
			
			// 刷新虚拟号码
			refreshNumber() {
				this.generatedNumber = this.generateVirtualNumber();
			},
			
			async toggleStatus(index) {
				const item = this.virtualNumbers[index];
				// 确定新的状态值
				const newStatus = item.status === '启用' ? 0 : 1; // 停用(0)或启用(1)
				const newStatusText = item.status === '启用' ? '停用' : '启用';
				
				try {
					// 调用API更新状态
					const response = await this.updateVirtualNumberStatus(item.number, newStatus);
					
					if (response.code === 0) {
						// 更新成功后更新本地状态
						item.status = item.status === '启用' ? '停用' : '启用';
						uni.showToast({
							title: `${newStatusText}成功`,
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: response.msg || `${newStatusText}失败`,
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('更新虚拟号码状态异常:', error);
					uni.showToast({
						title: '网络请求异常',
						icon: 'none'
					});
				}
			},
			
			async deleteNumber(index) {
				const item = this.virtualNumbers[index];
				
				uni.showModal({
					title: '确认删除',
					content: '确定要删除虚拟号码 ' + item.number + ' 吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 调用API删除虚拟号码
								const response = await this.deleteVirtualNumber(item.number);
								
								if (response.code === 0) {
									// 删除成功后更新本地列表
									this.virtualNumbers.splice(index, 1);
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: response.msg || '删除失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('删除虚拟号码异常:', error);
								uni.showToast({
									title: '网络请求异常',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			async addNumber() {
				if (!this.generatedNumber) {
					uni.showToast({
						title: '请先生成虚拟号码',
						icon: 'none'
					});
					return;
				}
				
				// 从本地存储获取用户手机号
				const localUserInfo = uni.getStorageSync('userInfo');
				if (!localUserInfo || !localUserInfo.phone) {
					uni.showToast({
						title: '未找到用户信息',
						icon: 'none'
					});
					return;
				}
				
				try {
					// 调用API创建虚拟号码
					const requestData = {
						virtualNumber: this.generatedNumber,
						level: this.levelOptions[this.levelIndex],
						rate: this.newRate,
						ownerPhone: localUserInfo.phone,
						status: this.statusIndex === 0 ? 1 : 0 // 启用为1，停用为0
					};
					
					const response = await this.addVirtualNumber(requestData);
					
					if (response.code === 0) {
						// 添加成功后更新列表
						this.virtualNumbers.push({
							number: this.generatedNumber,
							status: this.statusOptions[this.statusIndex],
							level: this.levelOptions[this.levelIndex],
							rate: this.newRate
						});
						
						// 重置选择和生成的号码
						this.levelIndex = 0;
						this.newRate = 10;
						this.statusIndex = 0;
						this.generatedNumber = '';
						
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: response.msg || '添加失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('添加虚拟号码异常:', error);
					uni.showToast({
						title: '网络请求异常',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
	}
	
	.header {
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		text-align: center;
	}
	
	.title {
		font-size: 36rpx;
		color: #333333;
		font-weight: bold;
	}
	
	.number-list {
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}
	
	.number-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.number-item:last-child {
		border-bottom: none;
	}
	
	.number-info {
		flex: 1;
	}
	
	.number {
		font-size: 32rpx;
		color: #333333;
		display: block;
		margin-bottom: 10rpx;
	}
	
	.status {
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 5rpx;
	}
	
	.status.active {
		background-color: #e8f4ff;
		color: #007AFF;
	}
	
	.status.inactive {
		background-color: #f0f0f0;
		color: #999999;
	}
	
	.number-actions {
		display: flex;
		gap: 20rpx;
	}
	
	.action-btn {
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		border-radius: 5rpx;
		background-color: #007AFF;
		color: #ffffff;
	}
	
	.action-btn.danger {
		background-color: #ff9900;
	}
	
	.action-btn.delete {
		background-color: #ff3b30;
	}
	
	.form-container {
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 30rpx;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.label {
		display: block;
		font-size: 28rpx;
		color: #333333;
		margin-bottom: 15rpx;
	}
	
	.input {
		width: 100%;
		height: 80rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.input:disabled {
		background-color: #eeeeee;
		color: #999999;
	}
	
	.picker {
		width: 100%;
		height: 80rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		line-height: 80rpx;
	}
	
	.picker-view {
		line-height: 80rpx;
		color: #333333;
	}
	
	.number-input-container {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}
	
	.refresh-btn {
		width: 150rpx;
		height: 80rpx;
		background-color: #007AFF;
		color: #ffffff;
		font-size: 28rpx;
		border-radius: 10rpx;
		white-space: nowrap;
	}
	
	.add-btn {
		width: 100%;
		height: 80rpx;
		background-color: #007AFF;
		color: #ffffff;
		font-size: 32rpx;
		border-radius: 10rpx;
	}
</style>